﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using InTREPWP.ViewModels;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace InTREPWP.Views
{
    public partial class Embarques : BasePage
    {
        private String _filtro;

        #region Page
        public Embarques()
        {
            _filtro = String.Empty;

            InitializeComponent();

            this.Loaded += new RoutedEventHandler(Embarques_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            NavigationContext.QueryString.TryGetValue("filtro", out _filtro);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Exit();
            base.OnBackKeyPress(e);
        }

        private void Exit()
        {
            while (NavigationService.BackStack.Any())
                NavigationService.RemoveBackEntry();

            this.IsHitTestVisible = this.IsEnabled = false;

            if (this.ApplicationBar != null)
                foreach (var item in this.ApplicationBar.Buttons.OfType<ApplicationBarIconButton>())
                    item.IsEnabled = false;
        }
        #endregion

        private void Embarques_Loaded(object sender, RoutedEventArgs e)
        {

            progressBar.Visibility = System.Windows.Visibility.Visible;
            MainListBox.Visibility = System.Windows.Visibility.Collapsed;

            BackgroundWorker bw = new BackgroundWorker();

            bw.RunWorkerCompleted += (s, ea) =>
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    progressBar.Visibility = System.Windows.Visibility.Collapsed;
                    MainListBox.Visibility = System.Windows.Visibility.Visible;
                    txtUltimaAtualizacao.Text = DateTime.Now.ToString();
                });

            bw.DoWork += (s, ea) => CarregaItens();

            bw.RunWorkerAsync();
        }

        private void CarregaItens()
        {

            using (IntrepService service = new IntrepService())
            {
                if (App.DadosLocais.Embarques.Count == 0)
                {
                    System.Threading.Thread.Sleep(3000);
                    var json = service.ListarEmbarques(_filtro);

                    var lista = JsonConvert.DeserializeObject<ObservableCollection<EmbarqueViewModel>>(json);

                    App.DadosLocais.Embarques = lista;
                }

                var model = App.DadosLocais.Embarques;

                if (!String.IsNullOrEmpty(_filtro))
                    model = (from x in model
                             where x.Destino.ToLower().Contains(_filtro.ToLower()) ||
                             x.Navio.ToLower().Contains(_filtro.ToLower()) ||
                             x.Produto.ToLower().Contains(_filtro.ToLower()) ||
                             x.Id.ToString().Contains(_filtro.ToLower())
                             select x).ToObservableCollection<EmbarqueViewModel>();

                Deployment.Current.Dispatcher.BeginInvoke(
                    () =>
                    {
                        DataContext = model;
                    }
                );
            }

            //Deployment.Current.Dispatcher.BeginInvoke(() =>
            //{
            //    progressBar.Visibility = System.Windows.Visibility.Collapsed;
            //});
        }

        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MainListBox.SelectedIndex == -1)
                return;

            var id = ((EmbarqueViewModel)MainListBox.SelectedItems[0]).Id;
            NavigationService.Navigate(new Uri("/Views/Detalhes.xaml?id=" + id, UriKind.Relative));

            MainListBox.SelectedIndex = -1;
        }


        #region ApplicationBar
        private void ApplicationBarMenuSobre_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Sobre.xaml", UriKind.Relative));
        }

        private void ApplicationBarSearch_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Busca.xaml", UriKind.Relative));
        }
        #endregion
    }
}